package web.common.internal.core.validation;

import web.common.core.annotation.Validation;
import web.common.core.validation.ValidationUtil;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * @author Jin Zheng
 * @since 1.0 2022-01-17
 */
public class ValidationInvocationHandler implements InvocationHandler {
	private final Object target;

	public ValidationInvocationHandler(Object target) {
		this.target = target;
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		boolean needValid = false;
		int i = 0;
		for (var param : method.getParameters()) {
			var annoValidation = param.getAnnotation(Validation.class);
			if (annoValidation != null) {
				ValidationUtil.valid(args[i], annoValidation.value());
				i++;
				continue;
			}
			if (param.getAnnotations().length > 0) {
				needValid = true;
			}
		}
		if (needValid) {
			ValidationUtil.valid(target, method, args);
		}

		return method.invoke(target, args);
	}

}
